package com.taocore.top.title.action;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.taobao.api.domain.Item;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taocore.top.title.domain.ItemsFilter;
import com.taocore.top.title.service.TaobaoService;
import com.taocore.utils.PagingOption;
import com.taocore.utils.PagingResult;

@Results({
	  @Result(location="optimize-items.jsp")
})
public class ItemsAction extends ActionBase{
	
	private ItemsFilter filter;
	private PagingOption option;
	private PagingResult<Item> pagingItems;
	
	public String execute() throws Exception
	{
		if (option == null)
		{
			option = new PagingOption();
			option.setLimit(30);
		}
		if (filter == null)
		{
			filter = new ItemsFilter();
		}
		_log.info("option: " + option);
		String topSession = getSessionId();
		List<Item> resultItems = null;
		long total = 0;
		if (filter.getSaleStatus() == ItemsFilter.STATUS_INVENTORY)
		{
			ItemsInventoryGetResponse rsp = TaobaoService.getInventory(null, filter.getKeyWord(), filter.getSellerCids(), filter.getBanner(), null, option.getCurrentPage() + 1, option.getLimit(), topSession);
			if (rsp.isSuccess())
			{
				resultItems = rsp.getItems();
				if (resultItems != null)
				{
					total = rsp.getTotalResults();
				}
			}
			else
			{
				error(rsp);
			}
		}
		else
		{
			ItemsOnsaleGetResponse rsp = TaobaoService.getOnSales(null, filter.getKeyWord(), filter.getSellerCids(), null, option.getCurrentPage() + 1, option.getLimit(), topSession);
			if (rsp.isSuccess())
			{
				resultItems = rsp.getItems();
				if (resultItems != null)
				{
					total = rsp.getTotalResults();
				}
			}
			else
			{
				error(rsp);
			}
		}
		pagingItems = new PagingResult<Item>();
		pagingItems.setItems(resultItems);
		pagingItems.setTotal(total);
		pagingItems.setOption(option);
		return SUCCESS;
	}

	@Action(value="items-selector", 
		    results={@Result(name="success", location="items.jsp")}
		  )
	public String select() throws Exception
	{
		return execute();
	}
	
	public void setFilter(ItemsFilter filter) {
		this.filter = filter;
	}

	public ItemsFilter getFilter() {
		return filter;
	}

	public void setOption(PagingOption option) {
		this.option = option;
	}

	public PagingOption getOption() {
		return option;
	}

	public void setPagingItems(PagingResult<Item> pagingItems) {
		this.pagingItems = pagingItems;
	}

	public PagingResult<Item> getPagingItems() {
		return pagingItems;
	}
}
